package com.xiaode.controller.admin.example;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.*;
import com.xiaode.common.model.dto.FindExampleDTO;
import com.xiaode.common.model.dto.example.StudentExampleTaskDTO;
import com.xiaode.common.model.dto.notice.NoticeDTO;
import com.xiaode.util.ChatUtil;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class ExampleService {
    
    /**
     * 根据榜样id删除榜样
     */
    public Ret delExample(Integer adminId, String exampleIds) throws Exception {
        List<Integer> exampleIdList = JSONUtil.toList(exampleIds, Integer.class);
        Kv kv = Kv.by("exampleIdList", exampleIdList);
        List<Example> exampleList = Example.dao.template("findExamplesByList", kv).find();
        for (int i = 0; i < exampleList.size(); i++) {
            Example example = exampleList.get(i);
            example.setIsDele(1);
        }

        Db.batchUpdate(exampleList, exampleList.size());
        return Ret.ok();
    }

    /**
     * 查询榜样
     */
    public Ret findExample(Admin admin, FindExampleDTO model, Kv kv, Integer page, Integer limit) throws Exception {
        Set<Integer> frameworkPermission = admin.get("frameworkPermission");
        List<Integer> permissionList = new ArrayList<>(frameworkPermission);
        Page<Record> paginate;
        if (permissionList.isEmpty()){
            paginate = Db.paginate(page,limit,"SELECT * ","FROM example WHERE founderIdentity IS NULL OR founderIdentity = 2");
        }else {
            kv.set("permission", permissionList);
            paginate = Db.template("findExamplePage", kv).paginate(page, limit);
        }
        List<Record> list = paginate.getList();
        for (int i = 0; i < list.size(); i++) {
            Record record = list.get(i);
            Integer id = record.getInt("id");
            //查询任务
            if (model.getTask() != null && model.getTask()) {
                List<Record> records = Db.find("SELECT setask.id,setask.content,setask.state  FROM `example` ex INNER JOIN student_example_task setask ON setask.studentId = ex.studentId WHERE ex.id = ? AND ex.isDele = 0", id);
                if (ObjectUtil.isAllEmpty(records) && record.get("studentId") == null) {
                    records = Db.find("SELECT et.id,et.content FROM `example` ex INNER JOIN example_task et ON ex.id = et.exampleId AND ex.isDele = 0 AND ex.id = ?", id);
                }
                record.put("task", records);
            }
            //查询使用人数
            if (model.getUseNum() != null && model.getUseNum()) {
                String name = record.get("name");
                int num = Db.queryInt("SELECT count(*) num FROM `example` ex WHERE ex.name = ? AND isDele = 0 AND studentId IS NOT NULL", name);
                record.put("useNum", num);
            }
            //查询创建人
            if (model.getFounder() != null && model.getFounder()) {
                Integer founderId = record.getInt("founderId");
                Integer founderIdentity = record.getInt("founderIdentity");
                if (founderIdentity == null) {
                    record.put("founder", "系统");
                } else if (founderIdentity == 1) {
                    Student student = Student.dao.findByIdLoadColumns(founderId, "name");
                    if (BeanUtil.isNotEmpty(student)) {
                        record.put("founder", student.getName());
                    }
                } else {
                    Admin founder = Admin.dao.findByIdLoadColumns(founderId, "name");
                    if (BeanUtil.isNotEmpty(founder)) {
                        record.put("founder", founder.getName());
                    }
                }
            }
        }

        return Ret.ok("exampleList", paginate);
    }

    /**
     * 修改榜样
     *
     * @param admin
     * @param exId
     * @param name
     * @param brief
     * @param taskStr
     * @return
     */
    @Before(Tx.class)
    public Ret updateExample(Admin admin, Integer exId, String name, Integer characterType, String brief, String taskStr, String reason, String pic) {

        Example example = Example.dao.findById(exId);
        example.setName(name == null ? example.getName() : name);
        example.setBrief(brief == null ? example.getBrief() : brief);
        example.setCharacterType(characterType == null ? example.getCharacterType() : characterType);
        example.setReason(reason == null ? example.getReason() : reason);
        example.setPictureUrl(pic);
        example.setSumState(4);

        example.update();
        //处理榜样任务
        if (taskStr != null) {
            List<StudentExampleTaskDTO> exampleTaskDTOS = JSONUtil.toList(taskStr, StudentExampleTaskDTO.class);
            if (example.getStudentId() == null) {
                ArrayList<ExampleTask> exampleTasks = new ArrayList<>(3);
                for (int i = 0; i < exampleTaskDTOS.size(); i++) {
                    StudentExampleTaskDTO exampleTaskDTO = exampleTaskDTOS.get(i);
                    ExampleTask exampleTask = ExampleTask.dao.findById(exampleTaskDTO.getId());
                    exampleTask.setContent(exampleTaskDTO.getContent());
                    exampleTask.setUpdateTime(LocalDateTime.now());
                    exampleTasks.add(exampleTask);
                }
                Db.batchUpdate(exampleTasks, 3);
            } else {
                //如果没有创建人,则是系统创建
//                ArrayList<StudentExampleTask> studentExampleTasks = new ArrayList<>(3);
//                for (int i = 0; i < exampleTaskDTOS.size(); i++) {
//                    StudentExampleTaskDTO exampleTaskDTO = exampleTaskDTOS.get(i);
//                    if (exampleTaskDTO.getId() != null) {
//                        StudentExampleTask exampleTask = StudentExampleTask.dao.findById(exampleTaskDTO.getId());
//                        exampleTask.setContent(exampleTaskDTO.getContent());
//                        exampleTask.setUpdateTime(LocalDateTime.now());
//                        exampleTask.setState(4);
//                        studentExampleTasks.add(exampleTask);
//                    } else {
//                        //学生创建的重要他人
//                        StudentExampleTask studentExampleTask = new StudentExampleTask();
//                        studentExampleTask.setContent(exampleTaskDTO.getContent());
//                        studentExampleTask.setScore(1);
//                        studentExampleTask.setCycle(1);
//                        studentExampleTask.setState(4);
//                        studentExampleTask.setStudentId(example.getStudentId());
//                        studentExampleTask.setUpdateTime(LocalDateTime.now());
//                        studentExampleTask.setAddTime(LocalDateTime.now());
//                        studentExampleTask.save();
//                    }
//                }
//                Db.batchUpdate(studentExampleTasks, 3);
            }
        }

        return Ret.ok();
    }

    /**
     * 添加榜样
     *
     * @param admin
     * @param name
     * @param brief
     * @param taskStr
     * @param characterType
     * @return
     */
    @Before(Tx.class)
    public Ret addExample(Admin admin, String name, String brief, String taskStr, Integer characterType, String reason, String pic) {
        //判断权限校验
//        String roleIds = admin.getRoleIds();
//        List<Integer> roleIdList = JSONUtil.toList(roleIds, Integer.class);
//        if (!roleIdList.contains(1) && !roleIdList.contains(3)) {
//            for (UploadFile uf : ufs) {
//                File file = uf.getFile();
//                if (file.exists()) {
//                    file.delete();
//                }
//            }
//            return Ret.fail().set("error", EnumError.NOT_HAVE_AUTHORITY.getObj());
//        }

        Example example = new Example();
        //榜样信息不存在 ,则直接添加
        example.setName(name);
        example.setBrief(brief);
        example.setCharacterType(characterType);
        example.setState(4);
        example.setSumState(4);
        example.setPictureUrl(pic);
        example.setAddTime(LocalDateTime.now());
        example.setUpdateTime(LocalDateTime.now());
        example.setFounderId(admin.getId());
        example.setFounderIdentity(2);
        example.setReason(reason);
        example.save();
        Example myExample = Example.dao.findFirst("SELECT id FROM `example` WHERE name = ? AND studentId is null", name);
        //处理榜样任务
        List<String> exampleTasks = JSONUtil.toList(taskStr, String.class);
        ArrayList<ExampleTask> exampleTaskList = new ArrayList<>(3);
        for (int i = 0; i < exampleTasks.size(); i++) {
            String exampleContent = exampleTasks.get(i);
            ExampleTask exampleTask = new ExampleTask();
            exampleTask.setExampleId(myExample.getId());
            exampleTask.setContent(exampleContent);
            exampleTask.setScore(1);
            exampleTask.setAddTime(LocalDateTime.now());
            exampleTask.setUpdateTime(LocalDateTime.now());
            exampleTaskList.add(exampleTask);
        }

        Db.batchSave(exampleTaskList, 3);
        return Ret.ok();
    }

    /**
     * 批量审核
     */
    @Before(Tx.class)
    public Ret examineExample(Admin admin, String exampleIds, Integer state, String reason) {
        Cache redis = Redis.use();

        //判断权限校验
        List<Integer> exampleIdList = JSONUtil.toList(exampleIds, Integer.class);
        Kv kv = Kv.by("exampleIdList", exampleIdList);
        List<Example> exampleList = Example.dao.template("findExamplesByList", kv).find();
        ArrayList<Example> examples = new ArrayList<>();
        ArrayList<StudentExampleTask> studentExampleTasks = new ArrayList<>();
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (int i = 0; i < exampleList.size(); i++) {
            
            Example example = exampleList.get(i);
            //筛选出未审核的榜样
            if (example.getSumState() == 2) {
                if (state != null) {
                    example.setExamineReason(reason);
                    example.setState(state);
                    example.setSumState(state);
                    example.setUpdateTime(LocalDateTime.now());
                    examples.add(example);
                    //榜样任务
                    List<StudentExampleTask> setList = StudentExampleTask.dao.find("SELECT * FROM example WHERE studentId = ? AND isDele = 0", example.getStudentId());
                    for(StudentExampleTask studentExampleTask : setList) {
                    	studentExampleTask.setState(state);
                    	studentExampleTasks.add(studentExampleTask);
                    }
                }
                
                //发送通知
                Student o = redis.get(Const.user.Student + example.getStudentId());
                NoticeDTO noticeDTO = new NoticeDTO();
                noticeDTO.setType(5);
                noticeDTO.setName(admin.getName());
                noticeDTO.setAccountId(admin.getAccountId());
                noticeDTO.setPic(admin.getAvatarUrl());
                noticeDTO.setContent(reason);
                arrayList.add(o.getAccountId());
                ChatUtil.sendNotice(JSONUtil.toJsonStr(noticeDTO), 1, arrayList);
            }
        }
        Db.batchUpdate(examples, examples.size());
        Db.batchUpdate(studentExampleTasks, studentExampleTasks.size());

        return Ret.ok();
    }
}